package com.elinkway.infinitemovies.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.VideoDataBean;
import com.le123.ysdq.BuildConfig;
import com.le123.ysdq.R;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class MoviesUtils {

    private final static String TAG = "MoviesUtils";

    private static String mOSVersion = "";

    private static String mDeviceModel = "";

    private static String mDeviceId = "";

    private static String mSdk = "";

    public static String timestamp2Recent(long times, Context context) {
        Resources res = context.getResources();
        long now = System.currentTimeMillis();
        long delta = (now - times) / 1000;
        if (delta < 60) {
            return res.getString(R.string.time_less_than_1_min);
        } else if (delta < 60 * 60) {
            return String.format(res.getString(R.string.time_less_than_1_hour), delta / 60);
        } else if (delta < 24 * 60 * 60) {
            return String.format(res.getString(R.string.time_less_than_1_day), delta / (60 * 60));
        } else {
            SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("M-dd", Locale.CHINESE);
            return localSimpleDateFormat.format(new Date(times));
        }
    }


    public static String seekHistroyTimeFormat(long seekHistroy, Context context) {

        Resources res = context.getResources();
        long tempSeekHistroy = seekHistroy / 1000;
        String formatSeekHistroy = null;
        if (tempSeekHistroy < 60) {

            formatSeekHistroy = res.getString(R.string.time_less_than_1_min);
        } else if (tempSeekHistroy < 10 * 60) {
            long second = tempSeekHistroy % 60;
            formatSeekHistroy =
                    String.format(res.getString(R.string.time_less_than_ten_minute),
                            tempSeekHistroy / 60, second >= 10 ? "" + second : "0" + second);

        } else if (tempSeekHistroy < 60 * 60) {
            long second = tempSeekHistroy % 60;
            formatSeekHistroy =
                    String.format(res.getString(R.string.time_less_than_1_hour_histroy),
                            tempSeekHistroy / 60, second >= 10 ? "" + second : "0" + second);
        } else {
            long second = tempSeekHistroy % 60;
            formatSeekHistroy =
                    String.format(res.getString(R.string.time_more_than_1_hour),
                            tempSeekHistroy / 60, second >= 10 ? "" + second : "0" + second);
        }
        return formatSeekHistroy;
    }


    /**
     * 得到客户端版本名
     */
    public static String getClientVersionName() {
        try {
            PackageInfo packInfo =
                    MoviesApplication.getInstance().getPackageManager()
                            .getPackageInfo(MoviesApplication.getInstance().getPackageName(), 0);
            return packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 得到客户端版本号
     */
    public static int getClientVersionCode() {
        try {
            PackageInfo packInfo =
                    MoviesApplication.getInstance().getPackageManager()
                            .getPackageInfo(MoviesApplication.getInstance().getPackageName(), 0);
            return packInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getClientChannel() {
        return ChannelUtil.getChannel(MoviesApplication.getInstance(), BuildConfig.DEFAULT_CHANNEL);
    }

    public static String optString(String str, String defStr) {
        if (TextUtils.isEmpty(str)) {
            return defStr;
        } else {
            return str;
        }
    }

    /**
     * 获取海报图上的描述
     *
     * @param video
     * @return zhangshuo 2014年6月5日 下午4:08:53
     */
    public static String getEpisodeInfo(Context context, VideoDataBean video) {
        if (null != video && !TextUtils.isEmpty(video.getVt())) {
            String vt = video.getVt();
            // 如果当前的影片类型为电影
            if (MoviesConstant.VT_MOVIE.equals(vt)) {
                return String.format("%.1f", video.getRating());
            } else if (MoviesConstant.VT_CARTOON.equals(vt) || MoviesConstant.VT_TV.equals(vt)) {
                if (!TextUtils.isEmpty(video.getIsend())
                        && !TextUtils.isEmpty(video.getNowepisodes())) {
                    StringBuffer nameBuff = new StringBuffer();
                    String isSend = video.getIsend();
                    // 如果正在更新剧集
                    if (MoviesConstant.EPISODE_UPDATE.equals(isSend)) {
                        nameBuff.append(context.getString(R.string.updateto));
                        nameBuff.append(video.getNowepisodes());
                        nameBuff.append(context.getString(R.string.episode));
                    } else if (MoviesConstant.EPISODE_UPDATE_END.equals(isSend)) {
                        // 如果是全集
                        nameBuff.append(context.getString(R.string.sum));
                        nameBuff.append(video.getNowepisodes());
                        nameBuff.append(context.getString(R.string.episode));


                    }
                    return nameBuff.toString();
                }
            } else if (MoviesConstant.VT_ZONGYI.equals(vt)) {
                try {
                    return "更新至" + video.getEpisodeList().get(0).getPorder() + "期";
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return video.getNowepisodes();
            } else {
                return "";
            }
        }
        return null;
    }


    public static String getPhoneImei() {
        String phoneImei = "";
        String UNKNOWN_IMEI = "ImeiUnknown";
        try {
            TelephonyManager telephonyManager = null;
            telephonyManager =
                    (TelephonyManager) MoviesApplication.getInstance().getSystemService(
                            Context.TELEPHONY_SERVICE);
            LogUtils.i(TAG, "after get system service.");
            if (null != telephonyManager) {
                phoneImei = telephonyManager.getDeviceId();
                Log.i(TAG, "mPhoneImei = " + phoneImei);
                if (phoneImei == null) {
                    phoneImei = UNKNOWN_IMEI;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            phoneImei = UNKNOWN_IMEI;
            Log.i(TAG, "in the catch.");
        }
        return phoneImei;
    }


    public static String getOSVersion() {
        if (TextUtils.isEmpty(mOSVersion)) {
            mOSVersion = android.os.Build.VERSION.RELEASE;
        }
        return mOSVersion;
    }

    public static String getDeviceModel() {
        if (StringUtil.isEmpty(mDeviceModel)) {
            try {
                mDeviceModel = URLEncoder.encode(android.os.Build.MODEL, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return mDeviceModel;
    }

    public static String getMacAddress() {
        try {
            WifiManager wifiManager =
                    (WifiManager) MoviesApplication.getInstance().getSystemService(
                            Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            return wifiInfo.getMacAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取deviceId
     *
     * @return
     */
    public static String getmDeviceId() {
        if (StringUtil.isEmpty(mDeviceId)) {
            try {
                String deviceId = ((TelephonyManager) MoviesApplication.getInstance().getSystemService(
                        Context.TELEPHONY_SERVICE)).getDeviceId();
                if (null == deviceId || deviceId.length() <= 0) {
                    mDeviceId = getSimulateDeviceID();
                } else {
                    mDeviceId = deviceId.replace(" ", "");
//                    mDeviceId = getSimulateDeviceID();
                }
            } catch (Exception e) {
                e.printStackTrace();
                mDeviceId = getSimulateDeviceID();
            }
        }
        return mDeviceId;
    }

    /**
     * 存储模拟 deviceId 的key
     */
    public static String DEVICEIDKEY = "deviceIdKey";

    private static String getSimulateDeviceID() {
        String defaultDeviceId = SharePreferenceManager.getVaule(MoviesApplication.getInstance(), DEVICEIDKEY, null);
        if (StringUtil.isEmpty(defaultDeviceId)) {
            defaultDeviceId = Utils.genRandomCode(15, 0);
            SharePreferenceManager.saveVaule(MoviesApplication.getInstance(), DEVICEIDKEY,
                    defaultDeviceId);
        }
        return defaultDeviceId;
    }

    /**
     * 获取手机的分辨率
     *
     * @param context
     * @return
     */
    public static String getResolution(Context context) {
        String resolution = "";
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//        DisplayMetrics outMetrics = new DisplayMetrics();
//        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = manager.getDefaultDisplay().getWidth();
        int height = manager.getDefaultDisplay().getHeight();
        resolution = width + "*" + height;
        return resolution;
    }

    public static String getMSdk() {
        if (TextUtils.isEmpty(mSdk)) {
            mSdk = android.os.Build.VERSION.SDK;
        }
        return mSdk;
    }

    public static boolean isProductLightning() {
        return BuildConfig.PRODUCT_NAME.equals(MoviesConstant.PRODUCT_LIGHTNING);
    }

    public static boolean isProductCjsp() {
        return BuildConfig.PRODUCT_NAME.equals(MoviesConstant.PRODUCT_CJSP);
    }

    public static boolean isProductYsdq() {
        return BuildConfig.PRODUCT_NAME.equals(MoviesConstant.PRODUCT_YSDQ);
    }

    public static boolean isProductKuaiKan() {
        return BuildConfig.PRODUCT_NAME.equals(MoviesConstant.PRODUCT_KUAIKAN);
    }

    public static String getLetvPushAppKey(Context context) {
        return context.getResources().getString(R.string.letv_push_app_key);
    }

    public static boolean isNets(String site) {
        return "nets".equals(site);
    }

    public static Boolean isLetv(String site) {
        return "letv".equals(site);
    }

    public static boolean isSelfProduct(String packageName){
        boolean isSelf = false;
        if(MoviesApplication.YINGSHIDAQUAN_PACKAGENAME.equals(packageName)){
            isSelf = true;
        }
        return isSelf;
    }

    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//含有字符和数字的字符串
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(62);// [0,62)

            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static String getMD5(String input) {
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(input.getBytes());
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            StringBuffer mdString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int m = 0; m < md.length; m++) {
                String mdHex = Integer.toHexString(md[m] & 0xFF);
                if (mdHex.length() < 2) {
                    mdString.append(0);
                }
                mdString.append(mdHex);
            }
            return mdString.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getSHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }
}
